import { type FC, useRef, memo } from 'react';
import { useMemoizedFn } from 'ahooks';
import { TriggerDialog, type TriggerDialogRefs } from '@/components';
import type { MoreMenuProps, MoreMenuContextType } from './types';
import { MoreMenuContext } from './context';
import Menus from './menus';

const MoreMenu: FC<MoreMenuProps> = (props) => {
  const { children, items } = props;
  const ref = useRef<TriggerDialogRefs>(null);

  const onClose = useMemoizedFn(() => {
    ref.current!.closeDialog();
  });

  const ctxVal: MoreMenuContextType = {
    items,
    onClose
  };

  return (
    <TriggerDialog
      ref={ref}
      trigger={children}
    >
      {() => {
        return (
          <MoreMenuContext.Provider value={ctxVal}>
            <Menus />
          </MoreMenuContext.Provider>
        );
      }}
    </TriggerDialog>
  );
}

export default memo(MoreMenu);